package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.bean.YiJi_Class;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.CustomProgressDialog;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Main_Send_NewsActivity extends Activity {
    private Button button_news_fenlei;
    private PopupWindow show_popupWindow;
    private ListView show_listview;
    private LinearLayout layout;
    private ArrayList<YiJi_Class> list = new ArrayList<YiJi_Class>();
    private MyAdapter mMyAdapter;
    //    private SharedPreferences sp;
//    private Editor ed;
    private EditText edittext_title, news_edittext_details;
    private int cat_id;
    private Button button_qiye_news_send;
    private CustomProgressDialog mCustomProgressDialog;
    private RelativeLayout send_news_back;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
                show_listview.setAdapter(mMyAdapter);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main__send__news);
        button_news_fenlei = (Button) findViewById(R.id.button_news_fenlei);
        mMyAdapter = new MyAdapter();
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        button_qiye_news_send = (Button) findViewById(R.id.button_qiye_news_send);

        edittext_title = (EditText) findViewById(R.id.edittext_title);
        news_edittext_details = (EditText) findViewById(R.id.news_edittext_details);
        send_news_back = (RelativeLayout) findViewById(R.id.send_news_back);

        send_news_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Main_Send_NewsActivity.this.finish();
            }
        });

        button_news_fenlei.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Photo_show();
                show_popupWindow.showAtLocation(findViewById(R.id.send_news), Gravity.BOTTOM, 0, 0);
                mCustomProgressDialog = CustomProgressDialog.createDialog(Main_Send_NewsActivity.this);
                mCustomProgressDialog.setCanceledOnTouchOutside(false);
                mCustomProgressDialog.show();
                get_news_fenlei();
                show_listview.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        button_news_fenlei.setText(list.get(arg2).getName());
                        button_news_fenlei.setTextColor(getResources().getColor(R.color.black3F));
                        cat_id = list.get(arg2).getId();
                        if (show_popupWindow != null) {
                            show_popupWindow.dismiss();
                            show_popupWindow = null;
                        }
                    }
                });
            }
        });

        button_qiye_news_send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (edittext_title.getText().toString().length() > 0) {
                    if (news_edittext_details.getText().toString().length() > 0) {
                        mCustomProgressDialog = CustomProgressDialog.createDialog(Main_Send_NewsActivity.this);
                        mCustomProgressDialog.setCanceledOnTouchOutside(false);
                        mCustomProgressDialog.show();
                        get_send_news();
                    } else {
                    }
                } else {
                    Toast.makeText(Main_Send_NewsActivity.this, "请先填写新闻标题", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void get_news_fenlei() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.news_fenlei,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        list.clear();
                        JSONArray array = response.getJSONArray("data");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            YiJi_Class mYiJi_Class = new YiJi_Class();
                            mYiJi_Class.setId(object.getInt("id"));
                            mYiJi_Class.setName(object.getString("cat_name"));
                            list.add(mYiJi_Class);
                        }
                        handler.sendEmptyMessage(1);
                    } else {
                        Toast.makeText(Main_Send_NewsActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
                if (show_popupWindow != null) {
                    show_popupWindow.dismiss();
                    show_popupWindow = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }


    public void get_send_news() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("title", edittext_title.getText().toString());
        map.put("cat", cat_id);
        map.put("details", news_edittext_details.getText().toString());
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.send_news,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        Toast.makeText(Main_Send_NewsActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                        Main_Send_NewsActivity.this.finish();
                    } else {
                        Toast.makeText(Main_Send_NewsActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    }

                    if (mCustomProgressDialog != null) {
                        mCustomProgressDialog.dismiss();
                        mCustomProgressDialog = null;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
                if (show_popupWindow != null) {
                    show_popupWindow.dismiss();
                    show_popupWindow = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    private void Photo_show() {
        layout = (LinearLayout) LayoutInflater.from(
                Main_Send_NewsActivity.this).inflate(
                R.layout.information_shoow_photo, null);
        show_listview = (ListView) layout.findViewById(R.id.information_photo_listview);

        show_listview.setCacheColorHint(0);
        if (show_popupWindow == null) {
            show_popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
            show_popupWindow.setBackgroundDrawable(new BitmapDrawable());
            show_popupWindow.setHeight(700);
            show_popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
            show_popupWindow.update();
            show_popupWindow.setOutsideTouchable(true);
            show_popupWindow.setFocusable(true);
            show_popupWindow.setContentView(layout);
        }
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int arg0) {
            return arg0;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder mHolder;
            if (convertView == null) {
                mHolder = new Holder();
                convertView = View.inflate(Main_Send_NewsActivity.this, R.layout.listview_item_layout, null);
                mHolder.place_text = (TextView) convertView.findViewById(R.id.place_text);
                convertView.setTag(mHolder);
            }
            mHolder = (Holder) convertView.getTag();
            mHolder.place_text.setText(list.get(position).getName());
            return convertView;
        }
    }

    class Holder {
        TextView place_text;
    }
}
